<?php
/**
 * Created by PhpStorm.
 * User: DELL-PC
 * Date: 2018/9/3
 * Time: 14:59
 */

namespace Application\Common\Controller;


use J\Schema\ICollection;
use J\Schema\Sprite;
use J\Schema\Syntax;
use J\Exception;

class Many
{
    /**
     * @var ICollection 当前表
     */
    protected $me;

    /**
     * Many constructor.
     * @param ICollection $me
     */
    public function __construct(ICollection $me)
    {
        $this->me = $me;
    }


    /**
     * 获取绑定数据
     * @param string $he 关联集合名
     * @param mixed $where 查询条件
     * @param bool $raw
     * @return mixed
     * @throws Exception
     */
    public function getBinds(string $he, $where = null, $raw = false)
    {
        if (empty($where)) $where = [$he, new Sprite('status', 0, '>')];

        $rows = $this->me->getLinker($he)->getCurd()
            ->setElements([$this->me->getName()])
            ->setWhere($where)
            ->setRaw($raw)
            ->select();
        // app()->debug(var_export($rows, true));
        return  array_column_unique($rows, $this->me->getName());
    }

    /**
     * 设置绑定数据
     *
     * @param string $he 关联集合名
     * @param mixed $hisWhere 关联条件
     * @param int[] $myIds
     * @throws Exception
     */
    public function setBinds(string $he, $hisWhere, $myIds)
    {
        $linker = $this->me->getLinker($he);
        $linker->getCurd()
            ->setWhere($hisWhere)
            ->setRecycle(false)
            ->delete();

        if(!is_array($myIds)) $myIds = [$myIds];

        foreach ($myIds as $v){
            $linker->getCurd()
                ->setElements([$he, $this->me->getName() => $v, 'status'=>1])
                ->add();
        }
    }

    /**
     * ElementUI 绑定数据 [he => he, me => ids]
     *
     * @param string $he
     * @throws Exception
     */
    public function setBindsElementUI(string $he)
    {
        $this->setBinds($he, [$he], $_REQUEST[Syntax::KEY_ID]);
    }

    /**
     * 解绑数据
     * @param string $he 关联集合名
     * @param mixed $where 查询条件
     * @throws Exception
     */
    public function dinb(string $he, $where)
    {
        $this->me->getLinker($he)->getCurd()
            ->setWhere($where)
            ->setRecycle(false)
            ->delete();
    }

    /**
     * ElementUI解绑
     * @param string $he
     * @throws Exception
     */
    public function dinbElementUI(string $he)
    {
        $this->dinb($he, [$he, $this->me->getName() => $_REQUEST[Syntax::KEY_ID]]);
    }
}